package p346题3;  
  
import java.io.File;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.nio.file.Files;  
import java.nio.file.Paths;  
import java.util.List;  
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
  
public class 题三新加要求版 {  
    public static void main(String[] args) {  
        String filePath = "C:\\Users\\munifeel\\eclipse-workspace2\\p346题3\\src\\p346题3\\goods.txt";
          
        List<String> lines = null;  
        try {  
            // 读取文件内容  
            lines = Files.readAllLines(Paths.get(filePath));  
              
            double sum = 0;  
            int count = 0;  
  
            // 解析价格数据  
            for (String line : lines) {  
                Matcher matcher = Pattern.compile("(\\d+)元/台").matcher(line);  
                if (matcher.find()) {  
                    double price = Double.parseDouble(matcher.group(1));  
                    sum += price;  
                    count++;  
                }  
            }  
  
            // 计算平均价格  
            double averagePrice = count > 0 ? sum / count : 0;  
            String averagePriceStr = String.format("%.2f", averagePrice);  
  
            // 输出平均价格  
            System.out.println("平均价格：" + averagePriceStr);  
  
            // 将平均价格追加写入到原文件  
            try (FileWriter writer = new FileWriter(filePath, true)) {  
                writer.write("\n平均价格：" + averagePriceStr);  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}